<?php
App::uses('AppModel', 'Model');
/**
 * Discipline Model
 *
 */
class Discipline extends AppModel {

	var $belongsTo = array(
		 'User' => array(
		 	'className' => 'User',
		 	'foreignKey' => '_user'
		 	),
		 'Team' => array(
		 		'className' => 'Team',
		 		'foreignKey' => '_team'
		 	)
		);

	var $hasAndBelongsToMany = array(
		'Courses' => array(
			'className' => 'Course',
			'joinTable' => 'courses_disciplines',
			'foreignKey' => 'discipline_id',
			'associationForeignKey' => 'course_id',
			'unique' => 'keepExisting',
			'conditions' => '',
			'fields' => '',
			'order' => '',
			'limit' => '',
			'offset' => '',
			'finderQuery' => '',
			'deleteQuery' => '',
			'insertQuery' => ''
		)
	);


	public function beforeSave($options = array()){
		return $this->validateUnique($this->data);
	}
	public function validateUnique($data){
		$discipline = $data['Discipline']['_team'];
		$team = $data['Discipline']['team'];
		$semester = $data['Discipline']['semester'];

		if(isset($data['Discipline']['id']))
			$row = $this->find('first', array('conditions'=> array('Discipline.team' => $team, 'Discipline._team' => $discipline, 'Discipline.id <>' => $data['Discipline']['id'], 'Discipline.semester' => $semester)));
		else
			$row = $this->find('first', array('conditions'=> array('Discipline.team' => $team, 'Discipline._team' => $discipline, 'Discipline.semester' => $semester)));

		return (!count($row));
	}
}
